package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.qiguliuxing.dts.db.dao.DtsRoleMapper;
import com.qiguliuxing.dts.db.domain.DtsRole;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class DtsRoleService {
	@Resource
	private DtsRoleMapper roleMapper;

	public Set<String> queryByIds(Integer[] roleIds) {
		Set<String> roles = new HashSet<String>();
		if (roleIds.length == 0) {
			return roles;
		}
		QueryWrapper<DtsRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().in(DtsRole::getId, roleIds);
		queryWrapper.lambda().eq(DtsRole::getEnabled, true);
		queryWrapper.lambda().eq(DtsRole::getDeleted, false);
		List<DtsRole> roleList = roleMapper.selectList(queryWrapper);

		for (DtsRole role : roleList) {
			roles.add(role.getName());
		}

		return roles;

	}

	public List<DtsRole> querySelective(String roleName, Integer page, Integer size, String sort, String order) {
		QueryWrapper<DtsRole> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(roleName)) {
			queryWrapper.lambda().like(DtsRole::getName, roleName);
		}
		queryWrapper.lambda().eq(DtsRole::getDeleted, false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsRole> iPage = new Page<>(page, size);
		return roleMapper.selectPage(iPage, queryWrapper).getRecords();
	}

	public DtsRole findById(Integer id) {
		return roleMapper.selectById(id);
	}

	public void add(DtsRole role) {
		role.setAddTime(LocalDateTime.now());
		role.setUpdateTime(LocalDateTime.now());
		roleMapper.insert(role);
	}

	public void deleteById(Integer id) {
		roleMapper.deleteById(id);
	}

	public void updateById(DtsRole role) {
		role.setUpdateTime(LocalDateTime.now());
		roleMapper.updateById(role);
	}

	public boolean checkExist(String name) {
		QueryWrapper<DtsRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsRole::getName, name);
		queryWrapper.lambda().eq(DtsRole::getDeleted, false);
		return roleMapper.selectCount(queryWrapper) != 0;
	}

	public List<DtsRole> queryAll() {
		QueryWrapper<DtsRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsRole::getDeleted, false);
		return roleMapper.selectList(queryWrapper);
	}
}
